package com.kye.express.business.jd.order_detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.after_sale.JDAfterSaleMainActivity;
import com.kye.express.business.jd.order_detail.model.JDOrderDetailModel;
import com.kye.express.databinding.ActivityIntegralOrderDetailBinding;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.jd.order_details.JDCheckGoodsAfterSaleBean;
import com.kye.model.bean.jd.order_details.JDOrderRouterInfoBean;
import com.kye.model.bean.jd.order_details.JDOrderRouterInfoResultDataBean;
import com.kye.model.bean.user.User;

import java.util.List;

import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 24/01/2018
 * @updated : 24/01/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class JDOrderDetailActivity extends BaseToolbarActivity implements JDOrderDetailConstract.JDOrderDetailView {

    private static final int REQUEST_AFTER_SALE = 1000;
    private ActivityIntegralOrderDetailBinding binding;
    private JDOrderDetailConstract.JDOrderDetailPresenter presenter;
    private JDOrderDetailModel orderDetailModel;
    private JDOrderRouterInfoResultDataBean jdOrderRouterInfoResultDataBean;
    private User user;
    private Dialog dialog;

    public static void startActivity(Context context, JDOrderDetailModel orderDetailModel) {
        Intent intent = new Intent(context, JDOrderDetailActivity.class);
        intent.putExtra(JDOrderDetailModel.class.getName(), orderDetailModel);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            orderDetailModel = getIntent().getParcelableExtra(JDOrderDetailModel.class.getName());
        } else {
            orderDetailModel = savedInstanceState.getParcelable(JDOrderDetailModel.class.getName());
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_integral_order_detail);
        presenter = new JDOrderDetailConstract.JDOrderDetailPresenter();
        initToolbat(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(JDOrderDetailModel.class.getName(), orderDetailModel);
        super.onSaveInstanceState(outState);
    }

    private void initToolbat(Bundle savedInstanceState) {
        setUpToolbar(binding.toolbar);
    }

    private void initViews(Bundle savedInstanceState) {

    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.orderRouterInto)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        JDOrderDetailRouterInfoActivity.startActivity(JDOrderDetailActivity.this, orderDetailModel, jdOrderRouterInfoResultDataBean.getOrderTrack());
                    }
                });
        RxView.clicks(binding.buyAgain)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        // todo : 再次购买

                    }
                });
        RxView.clicks(binding.applySaleService)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        // todo : 申请售后
                        presenter.checkAfterSaleAvailable(orderDetailModel, user);
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getOrderRouterInfos(orderDetailModel, user);
            }
        });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        this.user = user;
        binding.setData(orderDetailModel);
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void getJDOrderRouterInfoSuccess(JDOrderRouterInfoResultDataBean jdOrderRouterInfoResultDataBean) {
        this.jdOrderRouterInfoResultDataBean = jdOrderRouterInfoResultDataBean;
        Single
                .create(new SingleOnSubscribe<JDOrderDetailModel>() {
                    @Override
                    public void subscribe(SingleEmitter<JDOrderDetailModel> e) throws Exception {
                        List<JDOrderRouterInfoBean> orderTrack = jdOrderRouterInfoResultDataBean.getOrderTrack();
                        if (orderTrack != null && orderTrack.size() > 0) {
                            /**
                             * 物流信息显示路由的最新状态信息
                             */
                            JDOrderRouterInfoBean jdOrderRouterInfoBean = orderTrack.get(orderTrack.size() - 1);
                            orderDetailModel.setLogisticsInfo(jdOrderRouterInfoBean.getContent());
                        }
                        e.onSuccess(orderDetailModel);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<JDOrderDetailModel>() {
                    @Override
                    public void accept(JDOrderDetailModel jdOrderDetailModel) throws Exception {
                        binding.statusLayout.showContentView();
                        binding.setData(jdOrderDetailModel);
                    }
                });
    }

    @Override
    public void getJDOrderRouterInfoServerFailed(String msg) {
        ToastManager.showCenterForShort(msg);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void getJDOrderRouterInfoNetFailed(String msg) {
        ToastManager.showCenterForShort(msg);
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void checkAfterSaleSuccess(JDCheckGoodsAfterSaleBean jdCheckGoodsAfterSaleBean) {
        /**
         * todo : 售后跳转
         */
        Intent intent = JDAfterSaleMainActivity.newIntent(this, orderDetailModel);
        startActivityForResult(intent, REQUEST_AFTER_SALE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_AFTER_SALE && resultCode == Activity.RESULT_OK) {
            // 成功申请售后刷新界面
            binding.statusLayout.showLoadingView();
        }
    }

    @Override
    public void checkAfterSaleFailed(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_order_jd_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_contact:
                ToastManager.showCenterForShort("联系客服");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }


}
